// packageG/mycomponent/categoryCart/categoryCart.js
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    show: false,
    buttondisab: true,
    cart_ids: [],
    //配送方式
    showChoose: false,
    dispatch_types: [],
    radioChoose: '',
  },
  lifetimes: {
    attached() {
      let language = wx.getStorageSync("langIndex");
      this.setData({
        language: language.en
      })
      this.getCart();
    },
  },
  observers: {
    "show": function (newval) {
      if (newval) {
        this.setData({
          cart_ids: []
        })
        this.getCart();
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    closeChoose() {
      this.setData({
        showChoose: false
      })
    },
    toBuy() {
      this.submitGoods();
    },
    // 结算 -- 检查配送方式是否冲突
    checkGoods(event) {
      if (this.data.cart_ids.length == 0) {
        wx.showToast({
          icon: 'none',
          title: '请选择结算商品',
          duration: 1500
        });
        return;
      }
      console.log(this.data.cart_ids,'dddddd')
      if (this.data.cart_ids.length > 50) {
        wx.showToast({
          icon: 'none',
          title: '最多一次性只能下单50样商品',
          duration: 1500
        });
        return;
      }

      let urlStr = app.getNetAddresss("memberCart.checkout");
      urlStr += "&cart_ids=" + this.data.cart_ids.join(",");

      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.need_choose == 1) {
              this.setData({
                dispatch_types: res.data.dispatch_types,
                showChoose: true,
              });
            } else {
              this.submitGoods();
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              success(res) { }
            })
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    // 提交订单
    submitGoods() {
      let _cart_ids = [];
      if (this.data.showChoose && !this.data.radioChoose.toString()) {
        wx.showToast({
          icon: "none",
          title: "请先选择配送方式",
          duration: 1500,
        });
        return;
      }

      if (this.data.showChoose) {
        // 配送方式有冲突
        for (let i = 0; i < this.data.dispatch_types[this.data.radioChoose].member_carts.length; i++) {
          _cart_ids.push(
            this.data.dispatch_types[this.data.radioChoose].member_carts[i].id
          );
        }
      } else {
        _cart_ids = this.data.cart_ids;
      }

      // if (this.data.chooseType === 'rent') {
      //   wx.navigateTo({
      //     url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=rentCartBuy&cart_ids=' + JSON.stringify(_cart_ids)
      //   });
      // } else 
      // if (this.data.chooseType === 'buy') {
      wx.navigateTo({
        url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=-1&cart_ids=' + JSON.stringify(_cart_ids)
      });
      // }
    },
    typeChange(event) {
      this.setData({
        radioChoose: Number(event.detail),
      });
    },
    showTap() {
      this.setData({
        show: !this.data.show
      })
    },
    trggleCart() {
      this.setData({
        show: false
      })
      this.triggerEvent('cartShowClose', true)
    },
    numberLeft1(e) {
      if (!this.data.buttondisab) {
        return;
      }
      this.setData({
        buttondisab: false
      });
      wx.showLoading({
        title: '删除商品中'
      });
      let goodsT = e.currentTarget.dataset.item;
      let index = e.currentTarget.dataset.index;
      let id = goodsT.cart_id;
      let num = (Number(this.data.carts[index].total) - 1);
      if (num <= 0) {
        this.destroyData(id);
        return
      }
      this.addCart(id, num);
    },
    destroyData(_cid) {
      // 清除该购物车商品id
      let urlStr = app.getNetAddresss("member.member-cart.destroy");
      let json = {
        ids: _cid,
      };
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          var res = resdata.data;
          wx.hideLoading({
            success: (res) => {},
          })
          this.setData({
            buttondisab: true
          });
          if (res.result == 1) {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
            app.globalData.cart_num = app.globalData.cart_num - 1;
            let index = this.data.cart_ids.indexOf(_cid);
            if(index >= 0){
              this.data.cart_ids.splice(index,1)
            }
            this.setData({
              cart_ids:this.data.cart_ids
            })
            console.log(index,this.data.cart_ids,'dddddddddd')
            this.getCart();
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        },
      });
    },
    numberRight1(e) {
      console.log(e)
      if (!this.data.buttondisab) {
        return;
      }
      this.setData({
        buttondisab: false
      });
      wx.showLoading({
        title: '添加商品中'
      });
      let goodsT = e.currentTarget.dataset.item;
      let index = e.currentTarget.dataset.index;
      let id = goodsT.cart_id;
      let num = (Number(this.data.carts[index].total) + 1);
      this.addCart(id, num);
    },
    addCart(id, num) {
      let that = this;
      let urlStr = app.getNetAddresss('cart.list.updateNumV2');
      urlStr += '&id=' + id;
      urlStr += '&num=' + num;
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          wx.hideLoading({
            success: (res) => { },
          })
          var res = resdata.data;
          if (res.result == 1) {
            app.tips(res.msg);
            this.setData({
              buttondisab: true
            });
            that.getCart();
          } else {
            that.getCart();
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
            this.setData({
              buttondisab: true
            });
          }
        },
        fail: function (res) {
          console.log(res);
          wx.hideLoading({
            success: (res) => { },
          })
        }
      });
    },
    //全部清除购物车商品数据
    clearCart() {
      if (this.data.cart_ids.length == 0) {
        wx.showToast({
          icon: 'none',
          title: '请选择删除商品',
          duration: 1500
        });
        return;
      }
      let urlStr = app.getNetAddresss("cart.list.destroy");
      urlStr += "&ids=" + this.data.cart_ids.join(',');
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            this.getCart();
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: (res) => {
          console.log(res);
        }
      });
    },
    clickCount(e) {
      let total = e.currentTarget.dataset.total;
      this.setData({
        goodsCartsOld: total
      });
    },
    changeCount_2(e) {
      let that = this;
      let val = e.detail.value;
      let index = e.currentTarget.dataset.index;
      that.setData({
        ['carts[' + index + '].total']: val
      });
      let goodsCartsData = that.data.carts[index];
      if (goodsCartsData.total < 0) {
        wx.showToast({
          icon: 'none',
          title: "商品数量不能为负数",
          duration: 1500
        });
        that.setData({
          ['carts[' + index + '].total']: that.data.goodsCartsOld
        });
        return;
      }
      if (goodsCartsData.total < that.data.goodsCartsOld) {
        let lowerNum = that.data.goodsCartsOld - goodsCartsData.total;
        this.addCart(goodsCartsData.cart_id, val);
      } else if (goodsCartsData.total > that.data.goodsCartsOld) {
        let addNum = goodsCartsData.total - that.data.goodsCartsOld;
        this.addCart(goodsCartsData.cart_id, val);
      }
    },
    // 更新购物车数据
    getCart() {
      let urlStr = app.getNetAddresss("cart.list.otherPageCartList");
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(res.data, '2222222222')
            // this.setData({
            //   carts:res.data.list.length>0
            // })
            let carts = [];
            let cart_ids = this.data.cart_ids;
            if (res.data.list.length > 0) {
              for (let i = 0; i < res.data.list.length; i++) {
                for (let j = 0; j < res.data.list[i].carts.length; j++) {
                  carts.push(res.data.list[i].carts[j])
                }
              }
              for (let i = 0; i < res.data.list.length; i++) {
                for (let j = 0; j < res.data.list[i].carts.length; j++) {
                  if(cart_ids.indexOf(res.data.list[i].carts[j].cart_id) <0){
                    cart_ids.push(res.data.list[i].carts[j].cart_id);
                  }
                }
              }
            }
            this.setData({
              cart_ids,
              carts: carts,
              total_amount: res.data.total_amount
            })
            console.log(this.data.cart_ids,'cart_ids')
            let nums = 0;
            for (let i = 0; i < this.data.carts.length; i++) {
              nums += this.data.carts[i].total
            }
            this.setData({
              cartsNum: nums
            })
            // this.getCart(res.data);
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        },
      });
    },
  }
})